<template>
  <div id='imgtxtrptModel'>

    <div class='common-layout' id='imgtxtrpt' :loading='iloading'>
      <el-row>
        <el-col :span='24' v-for='(item, index) in fieldsAllRows' :key='index'>
          <ImgTxtRptTctField :labMainInfoObj='labMainInfoObj' :tempItem='item' :rptImages='rptImages'></ImgTxtRptTctField>
        </el-col>
      </el-row>
      <div class='multi-column-container'>
        <template v-for='(item, index) in fields' :key='index'>
          <div v-if='item.layer==1' class='layer'>
            <ImgTxtRptTctField :labMainInfoObj='labMainInfoObj' :tempItem='item.info' :rptImages='rptImages'></ImgTxtRptTctField>
          </div>
          <div v-if='item.layer==2' class='layer'>
            <span class='layer2'>{{ item.title }}:</span>
            <br />
            <template v-for='(childrenItem) in item.children'>
              <ImgTxtRptTctField :labMainInfoObj='labMainInfoObj' :tempItem='childrenItem' :rptImages='rptImages'></ImgTxtRptTctField>
            </template>
          </div>
          <div v-if='item.layer==3' class='layer'>
            <span class='layer2'>{{ item.title }}:</span>
            <br />
            <template v-for='(childrenGroup) in generateGroupArray(item.childrenGroup)'>
              <span class='layer3'>{{ childrenGroup.title }}</span>
              <br />
              <template v-for='(children2Item) in childrenGroup.children'>
                <ImgTxtRptTctField :labMainInfoObj='labMainInfoObj' :tempItem='children2Item' :rptImages='rptImages'></ImgTxtRptTctField>

              </template>
            </template>
          </div>
        </template>

      </div>
    </div>

  </div>
</template>

<script lang='ts' setup>
// 引入组件区 ==========
import {
  ref,
  reactive,
  watch,
  getCurrentInstance,
  PropType,
  onMounted,
  inject,
  defineEmits,
  defineExpose,
  crypto
} from 'vue';
import { IsEmpty, formatDateTime } from '@/utils/common'; //导入工具函数
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage';
import { funBdsJsResult } from '@/utils/Expression'; //函数公式
import ImgTxtRptTctField from '../img_txt_rpt/ImgTxtRptTctField.vue';
import html2canvas from 'html2canvas';
import { AppStore } from '@/stores/store';
import CryptoJS from 'crypto-js';

let labMainInfoObj: any = reactive({});
/**检验记录当前选中对象 */
// 全局变量定义区 ==========
let { proxy }: any = getCurrentInstance();
const apiPath = ref((window as any).apiUrl.VITE_SERVER_URL);
let store = AppStore();
let orgId = ref(null);
let iloading = ref(false);
let dialogVisible = ref(false);

//fixme:需要考虑这里还要不要留
const rptImages = inject('rptImages');

const fieldsAllRows = reactive([]);
const fields = reactive([]);
const textResults = reactive({});
let templateId = ref(null);

defineExpose({
  onSubmit,
  initPage,
  reviewValidateVsCountIsEqual,
  findTemplateItemListByTempId,
  capture
});

const proxyEmit = defineEmits(['updateTestList']);
// 父组件传值
let props = defineProps({
  currentRow: { type: Object as PropType<any>, required: true }
}) as any;

onMounted(() => {
  orgId = store.userInfo.orgId;

});

// 方法定义区 =============
function capture() {
  captureImg();
}
function captureImg() {
  let element = document.getElementById('imgtxtrpt');
  //document.querySelector("#imgtxtrpt")
  element.classList.add('modal-content');
  // 为元素添加类
  html2canvas(element, {
    scale: 5, // 增加分辨率
    useCORS: true, // 允许跨域请求
    logging: true, // 开启日志
    letterRendering: true, // 开启日志
    allowTaint: true, // 允许污染画布
    scrollX: 0,
    // scrollY: -window.scrollY, // 处理滚动条
    // height: element.scrollHeight, // 包含溢出部分的高度
    // width: element.scrollWidth, // 包含溢出部分的宽度
    ignoreElements: (element) => {
      // 忽略某些特定的元素，例如遮挡层
      return element.classList.contains('ignore-capture');
    }
  }).then(canvas => {
    // 将 canvas 转换为图片
    const imgData = canvas.toDataURL('image/png');
    uploadImage(imgData);
  });
}

const uploadImage = async (imgData) => {
  const response = await fetch(imgData);
  const blob = await response.blob();
  let formData = new FormData();
  let uploadFilePath = (window as any).apiUrl.VITE_SERVER_URL + '/lab/rptresultImage/uploadImgTxtFile';
  formData.append('id', "");
  formData.append('rptGroup', labMainInfoObj.rptGroup);
  formData.append('sampleda', labMainInfoObj.sampleda);
  formData.append('sampleNo', labMainInfoObj.sampleNo);
  formData.append('maininfoId', labMainInfoObj.id);
  formData.append('imageName', "rptimgtxt");
  formData.append('file', blob);
  try {
    const uploadResponse =
      await fetch(uploadFilePath, {
        method: 'POST',
        body: formData,
        headers: {
          Authorization: 'Bearer ' + localStorage.getItem('token')
        },
      });
    console.log(uploadResponse, "uploadResponse");
    document.getElementById('imgtxtrpt').classList.remove('modal-content');
  } catch (error) {
    console.error('网络请求错误', error);
  }
};

// 保存信息
function onSubmit(item: any) {
  if (!IsEmpty(item.resultDesc)) {
    item.rptGroup = labMainInfoObj.rptGroup;
    item.instrCode = labMainInfoObj.rptGroup;
    item.instrNa = labMainInfoObj.rptGroupNa;
    item.rptGroupName = labMainInfoObj.rptGroupNa;
    item.isNeedToReport = 1;
    item.itemNo = item.tempItemNo;
    item.itemNa = item.tempItemNa;
    item.sampleNo = labMainInfoObj.sampleNo;
    item.sampleda = labMainInfoObj.sampleda;
    item.rptResult = item.resultDesc?.slice(0, 255); //截取前249个字符
    item.reqNo = labMainInfoObj.reqNo;
    item.maininfoId = labMainInfoObj.id;
    submitForm(item);
  }
}

// 保存
const submitForm = (item: any) => {
  const url = '/lab/rptResult/saveImgTxtRptValue';
  proxy.$http
    //注意此处的数据条数
    .post(url, item)
    .then((res: any) => {
      if (res.status.code === 1) {
        if (IsEmpty(labMainInfoObj.id)) {
          //proxy.$emit
          labMainInfoObj.id = res.data.maininfoId;
          proxyEmit('updateTestList', {
            isSelCurRow: true,
            isRefreshRptResult: false,
            mainInfoId: res.data.maininfoId
          });
        }
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
    });
};

function initPage(mainInfoRow: any) {
  Object.assign(labMainInfoObj, mainInfoRow);
  if (IsEmpty(labMainInfoObj.id)) {
    if (IsEmpty(templateId.value)) {
      findTemplateItemList();
    } else {
      findTemplateItemListByTempId(templateId.value);
    }
  } else {
    findTemplateItemListByTempId(templateId.value);
  }
}

// 获取默认模板表单
function findTemplateItemList() {
  iloading.value = true;
  fields.length = 0; //放入数据前清空数据
  const url = '/lab/rptResult/findRptResultItemByTemp';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        sampleDaStr: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd'),
        rptGroup: labMainInfoObj.rptGroup,
        sampleNo: labMainInfoObj.sampleNo,
        reqNo: labMainInfoObj.reqNo,
        mainInfoId: labMainInfoObj.id
      }
    })
    .then((res: any) => {
      fields.length = 0; //放入数据前清空数据
      templateId.value = res.data[0].templateId;
      generateSortedArray(toItems(res.data));
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      console.log(err, '获取图报告单项目异常');
      VxeMessage('获取图报告单项目异常' + err, VxeNotifyType.error);
    });
}

// 根据模板ID获取图文报告文字结果
function findLabTemplateDetailByTempId(tempId) {
  iloading.value = true;
  fields.length = 0; //放入数据前清空数据
  const url = '/lab/rptResult/findLabTemplateDetailByTempId';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        templateId: tempId
      }
    })
    .then((ress: any) => {
      //textResults = {}; //放入数据前清空数据
      //遍历res.data根据itemNo生成{itemNo:[item]}数据
      ress.data.forEach(item => {
        if (!textResults[item.itemNo]) {
          textResults[item.itemNo] = [];
        }
        textResults[item.itemNo].push(item);
      });
      console.log(textResults, 'textResults');
      iloading.value = false;
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取图文报告文字结果异常', VxeNotifyType.error);
    });
}

// 获取指定模板表单
function findTemplateItemListByTempId(tempId) {
  templateId.value = tempId;
  iloading.value = true;
  fields.length = 0; //放入数据前清空数据
  // 获取指定模板表单
  let url = '/lab/rptResult/findRptResultItemByTempId';
  // 若maininfo存在则获取更新模板表单
  if (!IsEmpty(labMainInfoObj.id)) {
    url = '/lab/rptResult/upDataRptResultByTempId';
  }
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        templateId: templateId.value,
        sampleDaStr: formatDateTime(labMainInfoObj.sampleda, 'yyyy-MM-dd'),
        rptGroup: labMainInfoObj.rptGroup,
        sampleNo: labMainInfoObj.sampleNo,
        reqNo: labMainInfoObj.reqNo,
        mainInfoId: labMainInfoObj.id
      }
    })
    .then((res: any) => {
      fields.length = 0; //放入数据前清空数据
      fields.push(...
        generateSortedArray(toItems(res.data)));
    })
    .catch((err: any) => {
      iloading.value = false;
      VxeMessage('获取图报告单项目异常', VxeNotifyType.error);
    });
}

function toItems(data: any) {
  fieldsAllRows.length = 0
  let groupedData = data.reduce((acc, item) => {
    if (item['showRowCol'] == "all_row") {
      fieldsAllRows.push(item);
      return acc;
    }
    if (IsEmpty(item['detailGroup'])) {
      acc[item['tempItemNo']] = {
        id: item['tempItemNo'],
        title: '',
        layer: 1,
        children: [],
        childrenGroup: {},
        info: item,
        seq: item['seq']
      };
      return acc;
    }
    if (!IsEmpty(item['detailGroup'])) {
      let detailGroupStr = generateUniqueCode(item['detailGroup']);
      if (!acc[detailGroupStr]) {
        acc[detailGroupStr] = {
          id: detailGroupStr,
          title: item['detailGroup'],
          layer: 2,
          children: [],
          childrenGroup: {},
          info: {},
          seq: item['seq']
        };
      }
      if (!IsEmpty(item['detailGroup2'])) {
        acc[detailGroupStr]['layer'] = 3;
        let detailGroup2Str = generateUniqueCode(item['detailGroup2']);
        if (!acc[detailGroupStr]['childrenGroup'][detailGroup2Str]) {
          acc[detailGroupStr]['childrenGroup'][detailGroup2Str] = {
            title: item['detailGroup2'],
            layer: 3,
            children: [],
            seq: item['seq']
          };
        }
        acc[detailGroupStr]['childrenGroup'][detailGroup2Str]['children'].push(item);
      } else {
        acc[detailGroupStr]['children'].push(item);
      }
    }
    return acc;
  }, {});
  console.log(groupedData, 'toItems.groupedData');
  console.log(fieldsAllRows, 'fieldsAllRows.groupedData');
  return groupedData;
}

function generateSortedArray(groupedData: any) {
  const items = Object.values(groupedData);
  items.sort((a, b) => a.seq - b.seq);
  //遍历items写到fields中
  fields.length = 0;
  items.forEach(item => {
    fields.push(item);
  });
}

function generateGroupArray(groupedData: any) {
  const items = Object.values(groupedData);
  items.sort((a, b) => a.seq - b.seq);
  return items;
}

function showTypeCodeDrawer(item) {
  showDiagnosTempDrawer(item);
}

function colseTypeCodeDrawer() {
  diagnosTempDrawerRef.value.colseTypeCodeDrawer();
}

let diagnosTempDrawerRef = ref(null);

let sltItemFiled = null;

function showDiagnosTempDrawer(item) {
  sltItemFiled = item;
  diagnosTempDrawerRef.value.initPage({ diagnosTypeCode: item.typeCode });
}

function selectDiagnosTempInfo(row) {
  sltItemFiled.resultDesc = row.tempName;
  onSubmit(sltItemFiled);
}

function resultIsDisabled() {
  if (!IsEmpty(labMainInfoObj) && labMainInfoObj.isChk == '2') {
    return true;
  } else {
    return false;
  }
}

function generateUniqueCode(str) {
  return CryptoJS.MD5(str).toString();
}

/**审核验证，项目对照，检验结果数量是否相等 */
async function reviewValidateVsCountIsEqual() {
  let res = false;
  try {
    res = false;
  } catch (error) {
  }
  return res;
}

</script>

<style lang='scss' scoped>
.modal {
  position: fixed;
  top: 0;
  left: 150px;
  width: 1000px;
  height: 100%;
  background: #ffffff;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999999;
}
.modal-content {
  width: 1000px !important;
  height: 100% !important;
  transform: scale(0.7);
  transform-origin: 50% 0;
}
#imgtxtrpt {
  height: calc(80vh - 10px);
  padding: 21px;
  overflow: auto;
  .multi-column-container {
    column-count: 2; /* 分成两栏 */
    -moz-column-count: 2;
    -webkit-column-count: 2;
    /*height: 720px;  固定高度 */
    width: 1000px;
    overflow: hidden; /* 隐藏溢出内容 */

    column-gap: 16px; /* 栏间距 */
    -moz-column-gap: 16px;
    -webkit-column-gap: 16px;

    column-rule: 3px solid #e1dcce;
    -moz-column-rule: 3px solid #e1dcce;
    -webkit-column-rule: 3px solid #e1dcce;
  }
  //.multi-column-container::before {
  //  content: '';
  //  position: absolute;
  //  top: 0;
  //  bottom: 0;
  //  left: 492px;
  //  width: 16px;
  //  background-color: lightgray;
  //  z-index: -1;
  //}
  span {
    line-height: 32px;
  }

  .layer {
    .layer1 {
      padding-left: 16px;
    }
    .layer2 {
      font-weight: bold;
    }
    .layer3 {
      padding-left: 16px;
      float: left;
      color: #af4646;
      font-weight: lighter;
    }
  }

  // 中等尺寸时 配置扩展属性按钮
  .el-button--default {
    padding: 5px 11px;
  }

  table {
    border-collapse: collapse; /* 确保表格边框合并为单一边框 */
  }

  table,
  th,
  td {
    border: 1px solid black; /* 设置表格、表头、单元格的边框 */
    text-align: center;
  }

  .font14 {
    font-size: 14px;
  }
}

#imgtxtrpt::-webkit-scrollbar {
  display: none;
}
</style>

